package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.feign.WmUserFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.ApUserRealnameMapper;
import com.usian.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    public static final Short PASS_AUTH = 9;
    public static final Short FAIL_AUTH = 2;

    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WmUserFeign wmUserFeign;
    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Override
    public ResponseResult findPage(AuthDto dto) {

        if(dto==null ||dto.getStatus()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();


        QueryWrapper<ApUserRealname> queryWrapper =new QueryWrapper<>();

        if(dto.getStatus()!=null && dto.getStatus()!=3){
            queryWrapper.lambda().eq(ApUserRealname::getStatus,dto.getStatus());
        }
        Page page = new Page(dto.getPage(), dto.getSize());

        IPage result =page(page,queryWrapper);

        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }


    /**
     * 普通用户 申请成为自媒体用户 审核方法     审核（9，2） 9--》wemedia wmuser ---》article apauthor | 2---》失败原因--》
     * @param dto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        //1:参数校验
        if(dto==null ||status==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(status!=9 && status!=2){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUserRealname userRealname = this.getById(dto.getId());

        //2：更新apuserrealname表
        ApUserRealname apUserRealname= new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if(dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }
        apUserRealname.setUpdatedTime(new Date());
        this.updateById(apUserRealname);


        //2:判断审核状态 9
        if(status.equals(PASS_AUTH)){
            ResponseResult result = this.createWmUserAndApauthor(dto,userRealname.getUserId());
            if(result.getCode()!=0){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            //3:更新 apuser 表中的
            ApUser apUser =new ApUser();
            apUser.setId(userRealname.getUserId());
            apUser.setFlag(Short.valueOf("1")); //1：自媒体人
            apUserMapper.updateById(apUser);
            //int a=100/0;
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //保存wmuser 和apauthor 表数据
    private ResponseResult createWmUserAndApauthor(AuthDto dto,Integer userId){

        // 根据apuserrealname  userid  查询 apuser表 主键

        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据name 查询wmwuser表
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        if(wmUser==null){
            //4: false save wemedia wmuser
            wmUser = new WmUser();
            //设置ApUserId
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setStatus(9); //审核通过 状态
            wmUser.setPhone(apUser.getPhone());
            WmUser wmUser1 = wmUserFeign.saveWmUser(wmUser);

            //5: 作者表  query   save
            Integer apUserId = apUser.getId();
            ApAuthor apAuthor = apAuthorFeign.findByUserId(apUserId);
            if(apAuthor==null){
                apAuthor = new ApAuthor();
                apAuthor.setName(wmUser.getName());
                apAuthor.setType(2);
                apAuthor.setCreatedTime(new Date());
                apAuthor.setUserId(apUserId);
                apAuthor.setWmUserId(wmUser1.getId());
                apAuthorFeign.saveApAuthor(apAuthor);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}